<?php
define('GC_MODE', 'product');
class Shangku_GlobalCollect_Model_Api
{
	const DEVELOPMENT_API_URL = 'https://ps.gcsip.nl/wdl/wdl';
	const PRODUCT_API_URL = 'https://ps.gcsip.com/wdl/wdl';
	const XML_MERCHANT_ID_PATH = 'globalcollect/settings/merchant_id';
	
	private $_merchant_id = null;
	private $_cacheResponse = array();
	
	public function getMerchantId()
	{
		if(is_null($this->_merchant_id)){
			$this->_merchant_id = Mage::getStoreConfig(self::XML_MERCHANT_ID_PATH);
		}
		
		return $this->_merchant_id;
	}
	
	public function getCurrencyCode($order)
	{
		#return Mage::app()->getStore()->getCurrentCurrencyCode();
		return $order->getOrderCurrencyCode();
	}
	
	public function getCountryCode($order)
	{
		return $order->getBillingAddress()->getCountryId();
	}
	
	public function getLanguageCode()
	{
		return substr(Mage::app()->getLocale()->getLocaleCode(), 0, 2);
	}
	
	public function getFormatOrderAmout($order)
	{
		return sprintf('%.2f', $order->getGrandTotal()) * 100;
	}
	
	private function _getPaymentXml($paymentId, $order)
	{
		$returnUrl = Mage::getUrl('globalcollect/index/success', array('_secure' => true));
		$amount = $this->getFormatOrderAmout($order);
		$currencyCode = $this->getCurrencyCode($order);
		$countryCode = $this->getCountryCode($order);
		$languageCode = $this->getLanguageCode();
		
		return "<PAYMENT>
	                <CVVINDICATOR>1</CVVINDICATOR>
	                <RETURNURL>{$returnUrl}</RETURNURL>
	                <PAYMENTPRODUCTID>{$paymentId}</PAYMENTPRODUCTID>
	                <AMOUNT>{$amount}</AMOUNT>
	                <CURRENCYCODE>{$currencyCode}</CURRENCYCODE>
	                <COUNTRYCODE>{$countryCode}</COUNTRYCODE>
	                <LANGUAGECODE>{$languageCode}</LANGUAGECODE>
	                <HOSTEDINDICATOR>1</HOSTEDINDICATOR>
	            </PAYMENT>";
	}
	
	private function _getOrderXml($order)
	{
		$amount = $this->getFormatOrderAmout($order);
		$currencyCode = $this->getCurrencyCode($order);
		$countryCode = $this->getCountryCode($order);
		$languageCode = $this->getLanguageCode();
		$orderId = $order->getIncrementId();
		$firstName = $order->getCustomerFirstname();
		$lastName = $order->getCustomerLastname();
		$street = $order->getBillingAddress()->getData('street');
		$city = $order->getBillingAddress()->getCity();
		$zip = $order->getBillingAddress()->getPostcode();
		$marchantreference = time();
		return "<ORDER>
	                <ORDERID>{$orderId}</ORDERID>
	                <AMOUNT>{$amount}</AMOUNT>
	                <CURRENCYCODE>{$currencyCode}</CURRENCYCODE>
	                <LANGUAGECODE>{$languageCode}</LANGUAGECODE>
	                <COUNTRYCODE>{$countryCode}</COUNTRYCODE>
	                <SURNAME>{$lastName}</SURNAME>
	                <CITY>{$city}</CITY>
	                <FIRSTNAME>{$firstName}</FIRSTNAME>
	                <STREET>{$street}</STREET>
	                <ZIP>{$zip}</ZIP>
	                <MERCHANTREFERENCE>{$marchantreference}</MERCHANTREFERENCE>
	            </ORDER>";
	}
	
	private function _getMetaXml($version=1.0)
	{
		$merchantId = $this->getMerchantId();
		$ip = Mage::app()->getFrontController()->getRequest()->getClientIp();
		
		return "<META>
		            <MERCHANTID>{$merchantId}</MERCHANTID>
		            <IPADDRESS>{$ip}</IPADDRESS>
		            <VERSION>{$version}</VERSION>
		        </META>";
	}
	
	public function  getBodyXml($action, $orderId, $paymentId = null)
	{
		$order = Mage::getModel('sales/order')->loadByIncrementId($orderId);
		if(!$order->getId()){
			return '';
		}
		
		$xml = '';
		switch($action){
			case 'INSERT_ORDERWITHPAYMENT':
				$xml = "<XML>
							<REQUEST>
								<ACTION>{$action}</ACTION>" .
									$this->_getMetaXml() .
								'<PARAMS>' .
									$this->_getOrderXml($order) .
									$this->_getPaymentXml($paymentId, $order) .
								'</PARAMS>
							</REQUEST>
						</XML>';
				break;
			case 'GET_ORDERSTATUS':
				$xml = "<XML>
							<REQUEST>
								<ACTION>{$action}</ACTION>" .
								$this->_getMetaXml(2.0) .
								"<PARAMS>
									<ORDER>
										<ORDERID>{$orderId}</ORDERID>
									</ORDER>
								</PARAMS>
							</REQUEST>
						</XML>";
				break;
			default:
				throw new Exception('not support action!');
				break;
		}
		
		
		return $xml;
	}
	
	public function getApiUrl()
	{
		if(defined('GC_MODE') && GC_MODE == 'product'){
			return self::PRODUCT_API_URL;
		}
		
		return self::DEVELOPMENT_API_URL;
	}
	
	public function call($action, $orderId, $paymentId = null)
	{
		$client = new Varien_Http_Client($this->getApiUrl());
		
		$response = $client->setRawData($this->getBodyXml($action, $orderId, $paymentId), 'text/xml')
			->request('POST');
	
		return $this->_processResponse($response);
	}

	private function _processResponse($response)
	{
		return simplexml_load_string($response->getBody());
	}
}